package com.forte.orderdao;

import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Transactional;

@Transactional
public class OrderDAOImpl implements OrderDAO {
	
	private SessionFactory sessionFactory;
	
	public void setSessionFactory(SessionFactory sessionFactory){
		this.sessionFactory = sessionFactory;
	}
	
	protected final Session getCurrentSession(){
		return sessionFactory.getCurrentSession();
	}

	public void saveOrUpdate(Order order) {
		getCurrentSession().saveOrUpdate(order);
		
	}

	public void saveOrUpdate(OrderDetails orderDetails) {
		getCurrentSession().saveOrUpdate(orderDetails);		
	}

	public Order findOrderByOrderId(String orderId) {
		Query query = getCurrentSession().createQuery("from orders where orderId = :orderId");
		query.setParameter("orderId", orderId);
		return foundOrder(query.list());
	}
	
	@SuppressWarnings("rawtypes")
	public Order foundOrder(List list){
		Order orderFound = null;
		if (list.size() > 0){
			orderFound = (Order)list.get(0);
		}
		return orderFound;
	}

	@SuppressWarnings("unchecked")
	public List<Order> findOrderByOrderDate(Date orderDate) {
		Query query = getCurrentSession().createQuery("from orders where orderDate = :orderDate");
		query.setParameter("orderDate", orderDate);
		return (List<Order>) query.list();
	}

	@SuppressWarnings("unchecked")
	public List<Order> findOrderByStatus(String status) {
		Query query = getCurrentSession().createQuery("from orders where status = :status");
		query.setParameter("status", status);
		return (List<Order>) query.list();
	}

	public List<Order> findOrderByDeliveryId(int deliveryId) {
		Query query = getCurrentSession().createQuery("from orders where deliveryId = :deliveryId");
		query.setParameter("deliveryId", deliveryId);
		
		return (List<Order>) query.list();
	}

	public OrderDetails findOrderDetailsByOrderId(String orderId) {
		Query query = getCurrentSession().createQuery("from orderdetails where order_id = :order_id");
		query.setParameter("order_id", orderId);
		return foundOrderDetails(query.list());
	}
	
	public OrderDetails foundOrderDetails(List list){
		OrderDetails orderDetailFound = null;
		if(list.size() > 0){
			orderDetailFound = (OrderDetails) list.get(0);
		}
		
		return orderDetailFound;
	}

}
